<!--采购工作台-->
<template>
  <div class="procurement-workbench">
    <!-- 数据概览区域 -->
    <div class="data-overview">
      <div class="overview-title">数据概览 <span class="date">{{ currentDate }}</span></div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards" v-loading="loading.statistics">
        <div class="stat-card procurement-rate">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <div class="stat-label">本月采购完成率</div>
            <div class="stat-value">{{ statistics.procurementRate }}%</div>
          </div>
        </div>
        <div class="stat-card procurement-orders">
          <div class="stat-icon">📋</div>
          <div class="stat-content">
            <div class="stat-label">本月采购订单数</div>
            <div class="stat-value">{{ statistics.orderCount }}</div>
          </div>
        </div>
        <div class="stat-card procurement-amount">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-label">本月采购金额</div>
            <div class="stat-value">{{ formatAmount(statistics.procurementAmount) }}</div>
          </div>
        </div>
        <div class="stat-card supplier-count">
          <div class="stat-icon">🏢</div>
          <div class="stat-content">
            <div class="stat-label">本月供应商数量</div>
            <div class="stat-value">{{ statistics.supplierCount }}</div>
          </div>
        </div>
        <div class="stat-card inventory-value">
          <div class="stat-icon">📦</div>
          <div class="stat-content">
            <div class="stat-label">本月库存价值</div>
            <div class="stat-value">{{ formatAmount(statistics.inventoryValue) }}</div>
          </div>
        </div>
        <div class="stat-card quality-rate">
          <div class="stat-icon">✅</div>
          <div class="stat-content">
            <div class="stat-label">本月质检合格率</div>
            <div class="stat-value">{{ statistics.qualityRate }}%</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：待办事项 -->
      <div class="left-panel" v-loading="loading.todos">
        <div class="panel-header">
          <h3>待办事项</h3>
        </div>
        <div class="todo-section">
          <div class="todo-item">
            <div class="todo-number">{{ todos.pendingApproval }}</div>
            <div class="todo-label">待审核采购申请</div>
          </div>
          <div class="todo-item">
            <div class="todo-number">{{ todos.pendingConfirm }}</div>
            <div class="todo-label">待确认采购订单</div>
          </div>
          <div class="todo-item">
            <div class="todo-number">{{ todos.overdue }}</div>
            <div class="todo-label">已逾期采购订单</div>
          </div>
          <div class="todo-item">
            <div class="todo-number">{{ todos.qualityException }}</div>
            <div class="todo-label">入库质检异常</div>
          </div>
        </div>
      </div>

      <!-- 中间：走势图表 -->
      <div class="middle-panel" v-loading="loading.trends">
        <div class="panel-header">
          <h3>走势图表</h3>
        </div>
        <div class="chart-section">
          <!-- 年度目标 -->
          <div class="annual-target">
            <div class="target-label">年度目标</div>
            <div class="target-progress">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: trends.annualTarget.percentage + '%' }"></div>
              </div>
              <div class="progress-text">¥{{ formatAmount(trends.annualTarget.current) }} ({{ trends.annualTarget.percentage }}%)</div>
            </div>
            <div class="target-total">¥{{ formatAmount(trends.annualTarget.total) }}</div>
          </div>
          
          <!-- 本月目标 -->
          <div class="monthly-target">
            <div class="target-label">本月目标</div>
            <div class="target-progress">
              <div class="progress-bar">
                <div class="progress-fill" :style="{ width: trends.monthlyTarget.percentage + '%' }"></div>
              </div>
              <div class="progress-text">¥{{ formatAmount(trends.monthlyTarget.current) }} ({{ trends.monthlyTarget.percentage }}%)</div>
            </div>
            <div class="target-total">¥{{ formatAmount(trends.monthlyTarget.total) }}</div>
          </div>
          
          <!-- 采购趋势 -->
          <div class="procurement-trend">
            <div class="trend-label">采购趋势（最近12个月）</div>
            <div class="trend-chart">
              <div v-if="trends.procurementTrend && trends.procurementTrend.length > 0" class="trend-items">
                <div v-for="(item, index) in trends.procurementTrend.slice(-6)" :key="index" class="trend-item">
                  <div class="trend-month">{{ item.month }}</div>
                  <div class="trend-amount">¥{{ formatAmount(item.amount) }}</div>
                </div>
              </div>
              <div v-else class="no-trend-data">暂无趋势数据</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：常用功能 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>常用功能</h3>
        </div>
        <div class="function-grid">
          <div class="function-item">
            <div class="function-icon" style="background: #409eff;">📋</div>
            <div class="function-name">采购申请</div>
          </div>
          <div class="function-item">
            <div class="function-icon" style="background: #f56c6c;">📄</div>
            <div class="function-name">采购订单</div>
          </div>
          <div class="function-item">
            <div class="function-icon" style="background: #909399;">👥</div>
            <div class="function-name">供应商管理</div>
          </div>
          <div class="function-item">
            <div class="function-icon" style="background: #e6a23c;">📦</div>
            <div class="function-name">采购入库</div>
          </div>
          <div class="function-item">
            <div class="function-icon" style="background: #67c23a;">🔍</div>
            <div class="function-name">采购分析</div>
          </div>
          <div class="function-item">
            <div class="function-icon" style="background: #909399;">⚙️</div>
            <div class="function-name">采购设置</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部订单列表 -->
    <div class="orders-section">
      <div class="section-header">
        <h3>关键词</h3>
        <div class="search-controls">
          <input type="text" placeholder="请输入关键词" class="search-input" v-model="searchParams.keyword">
          <select class="filter-select" v-model="searchParams.status">
            <option value="">订单状态</option>
            <option value="">全部</option>
            <option value="0">待入库</option>
            <option value="1">部分入库</option>
            <option value="2">全部入库</option>
          </select>
          <input type="date" class="date-input" placeholder="期望到货时间" v-model="searchParams.expectedDate">
          <button class="search-btn" @click="searchOrders">搜索</button>
          <button class="reset-btn" @click="resetSearch">重置</button>
        </div>
      </div>
      
      <div class="orders-table">
        <table v-loading="loading.orders">
          <thead>
            <tr>
              <th>序号</th>
              <th>采购订单号</th>
              <th>供应商</th>
              <th>订单商品数量</th>
              <th>已入库数量</th>
              <th>订单总额</th>
              <th>已付款总额</th>
              <th>待付款总额</th>
              <th>已退货总额</th>
              <th>创建时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="procurementOrders.length === 0 && !loading.orders">
              <td colspan="10" style="text-align: center; padding: 40px; color: #999;">暂无数据</td>
            </tr>
            <tr v-for="(order, index) in procurementOrders" :key="order.id">
              <td>{{ index + 1 }}</td>
              <td><a href="#" class="order-link" @click="viewOrderDetail(order)">{{ order.orderNo }}</a></td>
              <td>{{ order.supplierName || '-' }}</td>
              <td>{{ order.purchaseQuantity || 0 }}</td>
              <td>{{ order.intoStorage || 0 }}</td>
              <td>¥{{ formatAmount(order.purchaseAmount) }}</td>
              <td>¥{{ formatAmount(order.amountPaid) }}</td>
              <td>¥{{ formatAmount(order.amountDue) }}</td>
              <td>¥{{ formatAmount(order.returnedQuantity * (order.purchaseAmount / order.purchaseQuantity || 0)) }}</td>
              <td>{{ formatDate(order.expectedStorageTime) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="table-pagination">
        <div class="pagination-info">
          <span>共 {{ pagination.total }} 条记录，每页 {{ pagination.pageSize }} 条</span>
        </div>
        <div class="pagination-controls">
          <button class="page-btn" @click="prevPage" :disabled="pagination.currentPage <= 1">
            上一页
          </button>
          <button 
            v-for="page in getPageNumbers()" 
            :key="page" 
            class="page-btn" 
            :class="{ active: page === pagination.currentPage }"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          <button class="page-btn" @click="nextPage" :disabled="pagination.currentPage >= pagination.totalPages">下一页</button>
          <select class="page-size-select" v-model="pagination.pageSize" @change="changePageSize">
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { procurementApi } from '@/api/procurement.js'

export default {
  name: 'ProcurementWorkbench',
  data() {
    return {
      // 统计数据
      statistics: {
        procurementRate: 0,
        orderCount: 0,
        procurementAmount: 0,
        supplierCount: 0,
        inventoryValue: 0,
        qualityRate: 0
      },
      
      // 待办事项
      todos: {
        pendingApproval: 0,
        pendingConfirm: 0,
        overdue: 0,
        qualityException: 0
      },
      
      // 趋势数据
      trends: {
        annualTarget: {
          current: 0,
          total: 0,
          percentage: 0
        },
        monthlyTarget: {
          current: 0,
          total: 0,
          percentage: 0
        },
        procurementTrend: []
      },
      
      // 采购订单列表
      procurementOrders: [],
      
      // 分页数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        totalPages: 1
      },
      
      // 搜索条件
      searchParams: {
        keyword: '',
        status: '',
        expectedDate: ''
      },
      
      // 加载状态
      loading: {
        statistics: false,
        todos: false,
        trends: false,
        orders: false
      }
    }
  },
  computed: {
    currentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      return `${year}年${month}月`
    }
  },
  
  mounted() {
    this.loadAllData()
  },
  
  methods: {
    // 加载所有数据
    async loadAllData() {
      await Promise.all([
        this.loadStatistics(),
        this.loadTodos(),
        this.loadTrends(),
        this.loadOrders()
      ])
    },
    
    // 加载统计数据
    async loadStatistics() {
      try {
        this.loading.statistics = true
        const response = await procurementApi.getProcurementStatistics()
        console.log('统计数据API响应:', response)
        if (response.code === 200) {
          console.log('后端返回的统计数据:', response.data)
          // 映射后端字段到前端字段
          this.statistics = {
            procurementRate: response.data.completionRate || 0,
            orderCount: response.data.orderCount || 0,
            procurementAmount: response.data.purchaseAmount || 0,
            supplierCount: response.data.supplierCount || 0,
            inventoryValue: response.data.inventoryValue || 0,
            qualityRate: response.data.qualityRate || 0
          }
          console.log('映射后的前端统计数据:', this.statistics)
        } else {
          console.error('API返回错误:', response)
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      } finally {
        this.loading.statistics = false
      }
    },
    
    // 加载待办事项
    async loadTodos() {
      try {
        this.loading.todos = true
        const response = await procurementApi.getProcurementTodos()
        console.log('待办事项API响应:', response)
        if (response.code === 200) {
          console.log('后端返回的待办事项数据:', response.data)
          // 映射后端字段到前端字段
          this.todos = {
            pendingApproval: response.data.pendingApprovals || 0,
            pendingConfirm: response.data.pendingConfirmations || 0,
            overdue: response.data.overdueOrders || 0,
            qualityException: response.data.qcAbnormal || 0
          }
          console.log('映射后的前端待办事项数据:', this.todos)
        } else {
          console.error('待办事项API返回错误:', response)
        }
      } catch (error) {
        console.error('获取待办事项失败:', error)
        this.$message.error('获取待办事项失败')
      } finally {
        this.loading.todos = false
      }
    },
    
    // 加载趋势数据
    async loadTrends() {
      try {
        this.loading.trends = true
        const response = await procurementApi.getProcurementTrends()
        console.log('趋势数据API响应:', response)
        if (response.code === 200) {
          console.log('后端返回的趋势数据:', response.data)
          // 映射后端字段到前端字段
          this.trends = {
            annualTarget: {
              current: response.data.yearTarget?.current || 0,
              total: response.data.yearTarget?.target || 0,
              percentage: response.data.yearTarget?.percentage || 0
            },
            monthlyTarget: {
              current: response.data.monthTarget?.current || 0,
              total: response.data.monthTarget?.target || 0,
              percentage: response.data.monthTarget?.percentage || 0
            },
            procurementTrend: response.data.procurementTrend || []
          }
          console.log('映射后的前端趋势数据:', this.trends)
        } else {
          console.error('趋势数据API返回错误:', response)
        }
      } catch (error) {
        console.error('获取趋势数据失败:', error)
        this.$message.error('获取趋势数据失败')
      } finally {
        this.loading.trends = false
      }
    },
    
    // 加载订单列表
    async loadOrders() {
      try {
        this.loading.orders = true
        const params = {
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          ...this.searchParams
        }
        const response = await procurementApi.getProcurementOrders(params)
        console.log('订单列表API响应:', response)
        if (response.code === 200) {
          console.log('后端返回的订单数据:', response.data)
          this.procurementOrders = response.data.records || []
          this.pagination.total = response.data.total || 0
          this.pagination.totalPages = Math.ceil(this.pagination.total / this.pagination.pageSize)
          console.log('映射后的前端订单数据:', this.procurementOrders)
        } else {
          console.error('订单列表API返回错误:', response)
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        this.$message.error('获取订单列表失败')
      } finally {
        this.loading.orders = false
      }
    },
    
    // 搜索订单
    searchOrders() {
      this.pagination.currentPage = 1
      this.loadOrders()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchParams = {
        keyword: '',
        status: '',
        expectedDate: ''
      }
      this.pagination.currentPage = 1
      this.loadOrders()
    },
    
    // 格式化金额
    formatAmount(amount) {
      if (!amount) return '0'
      if (amount >= 10000) {
        return (amount / 10000).toFixed(2) + '万'
      }
      return (amount || 0).toLocaleString()
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '-'
      return new Date(date).toLocaleDateString()
    },
    
    // 查看订单详情
    viewOrderDetail(order) {
      console.log('查看订单详情:', order)
      // 这里可以跳转到订单详情页面或打开弹窗
    },
    
    // 上一页
    prevPage() {
      if (this.pagination.currentPage > 1) {
        this.pagination.currentPage--
        this.loadOrders()
      }
    },
    
    // 下一页
    nextPage() {
      if (this.pagination.currentPage < this.pagination.totalPages) {
        this.pagination.currentPage++
        this.loadOrders()
      }
    },
    
    // 跳转到指定页
    goToPage(page) {
      if (page !== this.pagination.currentPage && page >= 1 && page <= this.pagination.totalPages) {
        this.pagination.currentPage = page
        this.loadOrders()
      }
    },
    
    // 获取页码数组
    getPageNumbers() {
      const pages = []
      const total = this.pagination.totalPages
      const current = this.pagination.currentPage
      
      if (total <= 7) {
        // 总页数小于等于7，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        // 总页数大于7，显示部分页码
        if (current <= 4) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        } else if (current >= total - 3) {
          pages.push(1)
          pages.push('...')
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          pages.push(1)
          pages.push('...')
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        }
      }
      
      return pages
    },
    
    // 改变每页显示数量
    changePageSize() {
      this.pagination.currentPage = 1
      this.loadOrders()
    }
  }
}
</script>

<style scoped>
.procurement-workbench {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 数据概览区域 */
.data-overview {
  margin-bottom: 20px;
}

.overview-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.date {
  color: #909399;
  font-weight: normal;
  font-size: 14px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.procurement-rate {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card.procurement-orders {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stat-card.procurement-amount {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stat-card.supplier-count {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-card.inventory-value {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  color: white;
}

.stat-card.quality-rate {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: #333;
}

.stat-icon {
  font-size: 24px;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 12px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

/* 主要内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 300px 1fr 300px;
  gap: 20px;
  margin-bottom: 20px;
}

/* 面板通用样式 */
.left-panel,
.middle-panel,
.right-panel {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.panel-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

/* 待办事项 */
.todo-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.todo-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.todo-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-right: 15px;
  min-width: 40px;
}

.todo-label {
  color: #606266;
  font-size: 14px;
}

/* 走势图表 */
.chart-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.annual-target,
.monthly-target,
.procurement-trend {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.target-label,
.trend-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.target-progress,
.trend-progress {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background: #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #67c23a);
  transition: width 0.3s;
}

.progress-text {
  font-size: 12px;
  color: #909399;
  min-width: 120px;
}

.target-total,
.trend-total {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

/* 趋势图表项目 */
.trend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.trend-item {
  flex: 1;
  min-width: 80px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  text-align: center;
  border: 1px solid #e4e7ed;
}

.trend-month {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.trend-amount {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.no-trend-data {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 20px;
}

/* 常用功能 */
.function-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.function-item:hover {
  background: #e6f7ff;
  transform: translateY(-2px);
}

.function-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  margin-bottom: 10px;
}

.function-name {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

/* 订单列表区域 */
.orders-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.search-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input,
.filter-select,
.date-input {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.search-btn,
.reset-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-btn {
  background: #409eff;
  color: white;
}

.reset-btn {
  background: #f56c6c;
  color: white;
}

/* 表格样式 */
.orders-table {
  overflow-x: auto;
  margin-bottom: 20px;
}

.orders-table table {
  width: 100%;
  border-collapse: collapse;
}

.orders-table th,
.orders-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

.orders-table th {
  background: #f5f7fa;
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.orders-table td {
  color: #606266;
  font-size: 14px;
}

.order-link {
  color: #409eff;
  text-decoration: none;
}

.order-link:hover {
  text-decoration: underline;
}

/* 分页样式 */
.table-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  color: #909399;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
  align-items: center;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.page-btn:hover {
  color: #409eff;
  border-color: #409eff;
}

.page-btn.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.page-btn.disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.page-size-select {
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  margin-left: 10px;
}
</style>